import java.util.LinkedList;
import java.util.Queue;

/**
 * 1926. 迷宫中离入口最近的出口
 * https://leetcode.cn/problems/nearest-exit-from-entrance-in-maze/description/
 */
class Solution2 {
    boolean[][] check;
    int[] dx = {0, 0, -1, 1};
    int[] dy = {-1, 1, 0, 0};
    public int nearestExit(char[][] maze, int[] entrance) {
        int m = maze.length, n = maze[0].length;
        check = new boolean[m][n];

        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[]{entrance[0], entrance[1]});
        check[entrance[0]][entrance[1]] = true;

        int ret = 0;
        
        while(!q.isEmpty()) {
            ret++;
            int sz = q.size();
            while(sz-- > 0) {
                int[] t = q.poll();
                for(int i = 0; i < 4; i++) {
                    int x = dx[i] + t[0], y = dy[i] + t[1];
                    if(x >= 0 && x < m && y >= 0 && y < n && !check[x][y] && maze[x][y] == '.') {
                        if(x == 0 || x == m - 1 || y == 0 || y == n - 1) return ret;
                        q.offer(new int[]{x, y});
                        check[x][y] = true;
                    }
                }
            }
        }

        return -1;
    }
}